//
//  CXStatusViewModel.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/22.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import YYText

/// 负责每一个cell的内容的布局和创建逻辑.将创建好的内容返还给CXStatusListViewModel
class CXStatusViewModel: NSObject {
    /// 模型
    var status: CXStatus?
    /// 头像
//    var headImage: UIImage?
    ///会员图标
    var mbImage: UIImage?
    /// 认证图标
    var verifiedImage: UIImage?
    /// 来自哪里
    var sourceText: String?
    /// 距离现在多久了
    var createText: String? {
        //重写getter 每次赋值都会重新计算 达到实时更新发布时间的目的
        return NSDate.sinaCreateDate(sinaStr: status?.created_at)?.dateDescription
    }
    ///  转发数量
    var repostButtonText: String?
    ///  评论数量
    var commentButtonText: String?
    ///  表态数量
    var attributeButtonText: String?
    /// 转发微博的内容
    var retweetText: String?
    /// 原创微博的富文本
    var originAttrString: NSMutableAttributedString?
    /// 转发微博的富文本
    var retwetAttrString: NSMutableAttributedString?
    ///  自定义创建方法
    init(status: CXStatus) {
        super.init()
        
        self.status = status
        //来源 距离现在多久
        getSourceText()
        
        //会员级别与认证
        getMBImage()
        getVerifiImage()
        
        //数量显示
        self.repostButtonText = getToolBarCountView(status.reposts_count, showName: "转发")
        self.commentButtonText = getToolBarCountView(status.comments_count, showName: "评论")
        self.attributeButtonText = getToolBarCountView(status.attitudes_count, showName: "赞")
        //转发内容,包括内容富文本
        getRetweetContext()
        //原文内容富文本
        self.originAttrString = getAttrString(status.text)
    }
}
// MARK: - 评论面板上三个按钮的文字显示
extension CXStatusViewModel {
    ///  获得来源
    private func getSourceText() {
        
        guard let sourceV = status?.source else {
            sourceText = "来自: "
            return
        }
        
        if let presource = sourceV.rangeOfString("\">") {
            if let postsource = sourceV.rangeOfString("</") {
                sourceText = "来自 \(sourceV.substringWithRange(presource.endIndex..<postsource.startIndex))"
            }
        }
    }

    private func getToolBarCountView(count: Int, showName: String) -> String {
        
        if count <= 0 {
            return showName
        } else {
            if count < 10000 {
                return "\(count)"
            } else {
                
                let res = "\(CGFloat(count / 1000) * 0.1)"
                let res1 = res.containsString(".0") ? res.stringByReplacingOccurrencesOfString(".0", withString: "") : res
                return "\(res1)万"
            }
        }
    }
    
    private func getRetweetContext() {
        //转发内容中 名字与正文都要齐全
        if let name = status?.retweeted_status?.user?.screen_name, text = status?.retweeted_status?.text {
            retweetText = "@\(name):\(text)"
            retwetAttrString = getAttrString(retweetText)
        } else {
            retweetText = nil
        }
    }
}
// MARK: - 富文本处理
extension CXStatusViewModel {
    
    private func getAttrString(text: String?) -> NSMutableAttributedString? {
        //text不能为nil
        guard let context = text else {
            return nil
        }
        /*
            一个一个的对表情串进行替换会引发遍历索引越界，倒序遍历又无法在同一个遍历中实现
            因此先将匹配结果模型保存（每一个元素是匹配模型），然后对这个结果数组进行倒序遍历处理
        */
        //1. 生成富文本 创建数组保存匹配模型
        let attrString = NSMutableAttributedString(string: context)
        var matchRes = [CXMatchResult]()
        
        //2. 匹配context里面的表情字符串
        (context as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (capCount, capString, capRange, _) -> Void in
            
            let capStr = capString.memory! as String
            let capRes = CXMatchResult(capturedRange: capRange.memory, capturedString: capStr)
            //保存每一个匹配结果模型
            matchRes.append(capRes)
        }
        //3. 倒序遍历 
        for value in matchRes.reverse() {
            
            let chs = value.capturedString
            //将遍历表情数组查找的过程封装交给工具类来处理
            if let emotion = CXEmotionTools.sharedTool.emotionWithChs(chs) {
                //获得了模型以后
                //进行处理
                let image = UIImage(named: "\(emotion.path!)/\(emotion.png!)", inBundle: CXEmotionTools.sharedTool.emotionBundle, compatibleWithTraitCollection: nil)
                
                /*
                  以下步骤包括生成富文本加入原文本 替换表情串为表情图片,采用YYText来处理
                */
//                let attachment = NSTextAttachment()
//                attachment.image = image
                let lineHeight = UIFont.systemFontOfSize(CXStatusFontSize).lineHeight
                
                //关键的一步
                let attrS = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: .ScaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignToFont: UIFont.systemFontOfSize(CXStatusFontSize), alignment: .Center)
                //将原富文本中的对应表情串替换
                attrString.replaceCharactersInRange(value.capturedRange, withAttributedString: attrS)
            }
        }
        //给匹配部分添加高亮等效果。由YYText来负责关键部分
        //给@ 部分添加高亮
        addHeighlitEffectTo(attributedString: attrString, regex: "@[^:^：^\\s^\\W]+")
        //给# 部分添加高亮
        addHeighlitEffectTo(attributedString: attrString, regex: "#[^#]+#")
        //给 网址 添加高亮
        addHeighlitEffectTo(attributedString: attrString, regex: "(http:|https:)//[^\\u2E80-\\u9FFF^\\s]+[0-9a-zA-Z]$")
        
        return attrString
    }
    
    private func addHeighlitEffectTo(attributedString attrString: NSMutableAttributedString, regex: String) {
        
        let sourceStr = attrString.string as NSString
        
        sourceStr.enumerateStringsMatchedByRegex(regex) { (count, capString, capRange, _) -> Void in
            
            attrString.addAttributes([NSForegroundColorAttributeName: UIColor(red: 80 / 255, green: 125 / 255, blue: 175 / 255, alpha: 1)], range: capRange.memory)
            //高亮区域背景层 边界
            let border = YYTextBorder(fillColor: UIColor(red: 177 / 255, green: 215 / 255, blue: 1, alpha: 1), cornerRadius: 3)
            /* RGB(r: 80, g: 125, b: 175) */
            let highlight = YYTextHighlight()
            highlight.setColor(UIColor(red: 80 / 255, green: 125 / 255, blue: 175 / 255, alpha: 1))
            highlight.setBackgroundBorder(border)
            
            //设置用户信息
            highlight.userInfo = ["content": capString.memory!]
            //设置高亮
            attrString.yy_setTextHighlight(highlight, range: capRange.memory)
        }
    }
}
// MARK: - 头像、会员级别与认证
extension CXStatusViewModel {
//    //头像
//    private func getHeadImage() {
//        headImage =
//    }
    //会员图标
    private func getMBImage() {
        
        let rank = status?.user?.mbrank ?? 0
        
        //有等级 就给会员图标赋值；没有则赋为nil
        if rank >= 1 && rank <= 6 {
            mbImage = UIImage(named: "common_icon_membership_level\(rank)")
        } else {
            mbImage = nil
        }
        
    }
    //认证图标
    private func getVerifiImage() {
        
        let verifi = status?.user?.verified ?? -1
        switch verifi {
        case 1:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
    }
}